import axios from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router/index'



const baseURL = 'https://big-event-vue-api-t.itheima.net/'

const instance = axios.create({
  //1.基础地址，超时时间
  baseURL,
  timeout: 10000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => { 
    //2.携带token
    const userStore = useUserStore()
    if(userStore.token){
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => 
  Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (res) => {
    //3.处理业务失败
    //4.摘取核心相应数据
    if(res.data.code === 0){
      return res
    }
    //处理业务失败，给错误提示，抛出错误
    ElMessage.error(res.data.message)
    return Promise.reject(res.data)
    
  },
  (err) => {
    
    //5.处理401错误
    //错误的特殊情况 => 401 权限不足 或 token过期 => 拦截到登录
    if(err.response?.status === 401){
      router.push('/login')
    }


    ElMessage.error(err.response.data.message||'服务异常')
    return Promise.reject(err)
    }
    
   
)

export default instance 
export { baseURL }